package com.nineclock.auth.intergration.processor;

import com.nineclock.auth.intergration.entity.IntergrationAuthenticationEntity;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 手机验证码方式认证处理器
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    private SysUserFeign userFeign;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SysUserDTO authenticate(IntergrationAuthenticationEntity entity) {

        // 1.获取手机号、验证码
        String mobile = entity.getAuthParameter("mobile");
        String password = entity.getAuthParameter("password");  // 验证码

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        // 2.从redis取出验证码，和传入的验证码进行对比
        String redisCode = (String) redisTemplate.opsForValue().get(SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile);

        if (!StringUtils.isEmpty(redisCode) && redisCode.equals(password)) {  // 验证码校验成功
            // 调用系统微服务feign接口，通过手机号获取用户信息
            SysUserDTO userDTO = userFeign.queryUser(mobile).getData();
            if (userDTO == null) {
                throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
            }

            // 重新设置password为传进来的验证码，否则框架在校验password时候，会失败
            userDTO.setPassword(encoder.encode(password));

            return userDTO;

        } else {
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

    }

    @Override
    public boolean support(IntergrationAuthenticationEntity entity) {
        // 判断是否该由自己处理，如果authType为sms，代表是手机验证码方式认证
        if (entity != null && entity.getAuthType() != null && entity.getAuthType().equals("sms")) {
            return true;
        }
        return false;
    }
}
